package com.zzyl.intercept;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 拦截器——鉴权
 * 拦截管理员端的按钮请求
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //用比较路径的方法
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        //1.获取请求头上的 token
        String token = request.getHeader(Constants.USER_TOKEN);
        if (token == null) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //2.解析 token
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if (ObjectUtil.isEmpty(claims)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //3.获得用户信息
        String user = (String) claims.get("user");
        //4.将用户信息转成对象
        UserVo userVo = JSONUtil.toBean(user, UserVo.class);

        //获取用户触发的按钮请求   POST/checkIn/create
        String url = request.getMethod() + request.getRequestURI();
        //获取 redis中存储的该用户授权路径信息
        String s = redisTemplate.opsForValue().get("user:resourceurl:" + userVo.getId());
        List<String> urlList = JSONUtil.toList(s, String.class);
        int i = 0;

        //比较该请求路径是否授权
        for (String str : urlList) {
            if(antPathMatcher.match(str,url)){
                //用户 id放在本地线程中
                UserThreadLocal.set(userVo.getId());
                return true;
            }
            i++;
        }
        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}
